<template>
   <div
        class="watermark-container" ref="parentRef">
        <slot></slot> 
        <!-- <img :src="`${watermarkBg}`" width="100" height="100" alt="watermark"  style="border: 2px solid #606; border-radius: 8px;"/> -->
    </div>
</template>




<script setup>
import {ref, defineProps,onMounted,onUnmounted } from 'vue'
import { userWatermarkBg } from '@/utils/userWatermarkBg'
const props = defineProps({
    text: {
        type: String,
        default: ''
    },
    fontSize: {
        type: Number,
        default: 40,
    },
    gap: {
        type: Number,
        default: 20
    },    
})
const parentRef = ref('')
const watermarkBg = ref('')
watermarkBg.value = userWatermarkBg(props);
console.log(watermarkBg.value)
let div;
function resetWatermark() {
    if(!parentRef.value) return ;// 防止页面刷新时，父元素还未渲染
    const base64 = userWatermarkBg(props);
    const size = 100;
    if(div){
        parentRef.value.removeChild(div); // 移除之前的div
    }    
    div = document.createElement('div');
    div.style.position = 'absolute';
    div.style.top = '0';
    div.style.left = '0';
    div.style.width = '100%';
    div.style.height = '100%';
    div.style.backgroundImage = `url(${base64})`;
    div.style.backgroundRepeat = 'repeat';
    div.style.backgroundSize = `${size}px ${size}px`;
    div.style.pointerEvents = 'none';
    div.style.inset = 0;
    parentRef.value.appendChild(div);
}
const ob = new MutationObserver((entries) => {
    for(const entry of entries){        
        // 修改属性可以重置水印
        if(entry.type === 'attributes' && entry.attributeName === 'style'){
            resetWatermark();
            return;
        }
        // 删除报错  还不清楚为什么
        for(const child of entry.removedNodes){
            if(child === div){
                resetWatermark();
                return;
            }
        }
      
    }
    console.log('watermark changed')       
});

onMounted(() => {
    ob.observe(parentRef.value, {
        attributes: true,
        childList: true,
        subtree: true
    });
    resetWatermark()
})
onUnmounted(() =>{
    ob.disconnect();
})



</script>
<style scoped>
.watermark-container {
    position: relative;
    width: 400px;
    height: 400px;
 
}
</style>

